package cc.autoapi.pucong.auto.flow.core.flow.execNode.utils;


import cc.autoapi.pucong.auto.flow.core.flow.execNode.exception.AutoDesignException;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.selfenum.AiTypeEnum;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Objects;

/**
 * ai 提示词获取
 *
 * @description:
 * @author: cong.pu
 * @create: 2024-10-14 08:47
 **/
@Slf4j
public class AiJsonUtils {

    /**
     * 获取ai 提示词
     *
     * @param type
     * @return
     */
    public static String getPromptFromJsonFile(AiTypeEnum type) {
        String filePath = getSystemBasePath() + File.separator + "ai" + File.separator + "prompt.json";
        File file = new File(filePath);
        InputStream config = null;
        try {
            if (file.exists()) {
                config = new FileInputStream(file);
            } else {
                config = AiJsonUtils.class.getResourceAsStream("/ai/prompt.json");
            }
            JSONArray array = JSON.parseObject(config, JSONArray.class);
            for (Object object : array) {
                JSONObject data = (JSONObject) object;
                if (Objects.equals(data.getInteger("type"), type.getValue())) {
                    String content = data.getString("content");
                    return content;
                }
            }
            return null;
        } catch (Exception e) {
            log.error("搜索配置文件解析异常", e);
            throw new AutoDesignException("搜索配置文件解析异常");
        }
    }

    public static JSONArray getToolsJon() {
        String filePath = getSystemBasePath() + File.separator + "ai" + File.separator + "tools.json";
        File file = new File(filePath);
        InputStream config = null;
        try {
            if (file.exists()) {
                config = new FileInputStream(file);
            } else {
                config = AiJsonUtils.class.getResourceAsStream("/ai/tools.json");
            }
            JSONArray array = JSON.parseObject(config, JSONArray.class);
            return array;
        } catch (Exception e) {
            log.error("tools配置文件解析异常", e);
            throw new AutoDesignException("tools配置文件解析异常");
        }
    }

    private static String getSystemBasePath() {
        String usrdir = System.getProperty("user.dir");
        String basePath = usrdir + File.separator + "data";
        return basePath;
    }
}
